<!-- 押运员管理 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @selection-change="selectionChange"
    >
      <template slot-scope="{ disabled, size }" slot="expireDateSearch">
        <el-switch :disabled="disabled" :size="size" v-model="query.expireDate">
        </el-switch>
      </template>
      <template slot="menuLeft">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          @click="batchDelete"
          >删除</el-button
        >
        <importBtn
          customUrl="/api/blade-tms/supercargoinfo/EscortManagementController/importIntoExcel"
          @refresh="onLoad(page)"
        />
        <downTemplateBtn
          customUrl="/api/blade-tms/supercargoinfo/EscortManagementController/export"
        />
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button
          type="text"
          size="mini"
          icon="el-icon-edit"
          @click.stop="rowEdit(row, index)"
          >编辑</el-button
        >
        <el-button
          type="text"
          size="mini"
          icon="el-icon-view"
          v-if="row.approvalStatus == '已驳回'"
          @click.stop="viewReject(row)"
          >驳回原因</el-button
        >
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, update, deleteSupercargo } from "@/api/basedata/supercargo";
import { phoneBind } from "@/api/basedata/carriers";
import { cardid } from "@/util/validate";
import importBtn from "../components/importBtn";
import downTemplateBtn from "../components/downTemplateBtn";

export default {
  data() {
    var validateIdCardNo = (rule, value, callback) => {
      if (!cardid(value)[0]) {
        callback();
      } else {
        callback(new Error(cardid(value)[1]));
      }
    };
    var validatePhone = (rule, value, callback) => {
      if (value) {
        if (!/^1[0-9]{10}$/.test(value)) {
          callback(new Error("请输入正确的联系电话"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入联系电话"));
      }
    };
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        height: "auto",
        calcHeight: 30,
        tip: false,
        selection: true,
        searchShow: false,
        searchMenuSpan: 6,
        border: true,
        editBtn: false,
        labelWidth: "180",
        menuWidth: "250",
        column: [
          {
            label: "姓名",
            prop: "name",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入姓名",
                trigger: "blur",
              },
            ],
          },
          {
            label: "联系电话",
            prop: "phone",
            search: true,
            rules: [
              // {
              //   required: true,
              //   message: "请输入联系电话",
              //   trigger: "blur",
              // },
              { required: true, trigger: "blur", validator: validatePhone },
            ],
          },
          {
            label: "从业资格证号",
            prop: "certificateWorkNo",
            rules: [
              {
                required: true,
                message: "请输入从业资格证号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "从业资格证有效期",
            type: "datetime",
            prop: "validityPeriod",
            hide: true,
            showColumn: false,
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            rules: [
              {
                required: true,
                message: "请选择从业资格证有效期",
                trigger: "change",
              },
            ],
          },
          {
            label: "身份证号",
            prop: "idCardNo",
            rules: [
              {
                validator: validateIdCardNo,
                required: true,
                trigger: "blur",
              },
            ],
          },
          {
            label: "身份证有效期",
            type: "datetimerange",
            prop: "idCardValidDate",
            hide: true,
            showColumn: false,
            defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            startPlaceholder: "请选择开始日期",
            endPlaceholder: "请选择结束日期",
            rules: [
              {
                required: true,
                message: "请选择身份证有效期",
                trigger: "change",
              },
            ],
          },
          {
            label: "备注",
            prop: "remark",
            hide: true,
            showColumn: false,
          },
          {
            label: "审核状态",
            prop: "approvalStatus",
            type: "select",
            editDisplay: false,
            addDisplay: false,
            props: {
              label: "value",
              value: "key",
            },
            search: true,
            dicUrl: `/api/blade-tms/common/SelectEnum?name=approval`,
          },
          {
            label: "创建时间",
            type: "datetime",
            prop: "createTime",
            search: true,
            searchRange: true,
            editDisplay: false,
            addDisplay: false,
            hide: true,
            showColumn: false,
            defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            startPlaceholder: "请选择开始日期",
            endPlaceholder: "请选择结束日期",
          },
          {
            label: "即将到期",
            prop: "expireDate",
            search: true,
            searchRange: true,
            editDisplay: false,
            addDisplay: false,
            hide: true,
            showColumn: false,
            searchSpan: 3,
          },
          {
            label: "身份证正面照片上传",
            prop: "idCardPicFront",
            hide: true,
            showColumn: false,
            type: "upload",
            span: 12,
            listType: "picture-img",
            propsHttp: {
              res: "data",
              name: "originalName",
              url: "link",
            },
            action: "/api/blade-resource/oss/endpoint/put-file-attach",
            rules: [
              {
                required: true,
                message: "请上传身份证正面照片",
                trigger: "change",
              },
            ],
          },
          {
            label: "身份证背面照片上传",
            prop: "idCardPicBack",
            hide: true,
            showColumn: false,
            type: "upload",
            span: 12,
            listType: "picture-img",
            propsHttp: {
              res: "data",
              name: "originalName",
              url: "link",
            },
            action: "/api/blade-resource/oss/endpoint/put-file-attach",
            rules: [
              {
                required: true,
                message: "请上传身份证背面照片",
                trigger: "change",
              },
            ],
          },
          {
            label: "从业资格证上传",
            prop: "certificateWorkPic",
            hide: true,
            showColumn: false,
            type: "upload",
            span: 12,
            listType: "picture-img",
            propsHttp: {
              res: "data",
              name: "originalName",
              url: "link",
            },
            action: "/api/blade-resource/oss/endpoint/put-file-attach",
            rules: [
              {
                required: true,
                message: "请上传从业资格证",
                trigger: "change",
              },
            ],
          },
        ],
      },
      data: [],
      selectionList: [], //选择数据
    };
  },
  components: { importBtn, downTemplateBtn },
  computed: {},
  watch: {
    "query.expireDate"(val) {
      if (val === false || val === true) {
        this.page.currentPage = 1;
        this.onLoad(this.page, this.query);
      }
    },
  },
  methods: {
    rowEdit(row, index) {
      this.$refs.crud.rowEdit(row, index);
      this.form = {
        ...row,
        idCardValidDate: [row.idCardValidStart, row.idCardValidEnd],
      };
    },
    //查看驳回原因
    viewReject(row) {
      this.$alert(row.remarkReject, "驳回原因", {
        showCancelButton: true,
        showConfirmButton: false,
        cancelButtonText: "关闭",
      });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (this.query.expireDate) {
        this.query = {
          ...params,
          expireDate: this.query.expireDate,
        };
      } else {
        this.query = params;
      }
      // this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      let query = Object.assign(params, this.query);
      if (query.createTime) {
        query = {
          ...query,
          start: query.createTime ? query.createTime[0] : "",
          end: query.createTime ? query.createTime[1] : "",
        };
        delete query.createTime;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, query).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.$nextTick(() => {
          this.$refs.crud.$refs.table.doLayout();
        });
      });
    },
    //编辑
    rowUpdate(row, index, done, loading) {
      let updateData = {
        ...row,
        idCardValidStart: row.idCardValidDate ? row.idCardValidDate[0] : "",
        idCardValidEnd: row.idCardValidDate ? row.idCardValidDate[1] : "",
      };
      update(updateData).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    //新增
    rowSave(form, done, loading) {
      let updateData = {
        ...form,
        idCardValidStart: form.idCardValidDate ? form.idCardValidDate[0] : "",
        idCardValidEnd: form.idCardValidDate ? form.idCardValidDate[1] : "",
        certificateDriverValidStart: form.certificateDriverValidDate
          ? form.certificateDriverValidDate[0]
          : "",
        certificateDriverValidEnd: form.certificateDriverValidDate
          ? form.certificateDriverValidDate[1]
          : "",
      };
      loading();
      update(updateData).then(
        ({ data }) => {
          if (data.code === 200 && data.success) {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            done(updateData);
          } else if (data.code === 206) {
            this.$confirm("系统中已存在该押运员，是否进行绑定?", "提示", {
              confirmButtonText: "绑定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                phoneBind({
                  number: updateData.phone,
                  type: "escort",
                }).then(
                  () => {
                    this.onLoad(this.page);
                    this.$message({
                      type: "success",
                      message: "操作成功!",
                    });
                    done(updateData);
                  },
                  (error) => {
                    window.console.log(error);
                  }
                );
              })
              .catch(() => {
                this.onLoad(this.page);
                done(updateData);
              });
          }
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    //删除
    rowDel(form) {
      this.delSupercargo([form.id]);
    },
    //批量删除
    batchDelete() {
      if (this.selectionList.length <= 0) {
        this.$message({
          message: "请选择押运员",
          type: "warning",
        });
        return false;
      }
      let ids = this.selectionList.map((item) => {
        return item.id;
      });
      this.delSupercargo(ids);
    },
    delSupercargo(ids) {
      this.$confirm("是否确定删除所选押运员?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteSupercargo({ ids: ids }).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => {});
    },
    //多选
    selectionChange(list) {
      this.selectionList = list;
    },
  },
};
</script>

<style></style>
